package com.itzhihao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzhihao.common.constant.ExistStatus;
import com.itzhihao.common.constant.ProductStatus;
import com.itzhihao.common.constant.StoreStatus;
import com.itzhihao.entity.Product;
import com.itzhihao.entity.Store;
import com.itzhihao.entity.vo.ProductVo;
import com.itzhihao.mapper.ProductMapper;
import com.itzhihao.service.IProductService;
import com.itzhihao.service.IStoreService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements IProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private IStoreService storeService;

    @Override
    public TableDataInfo getBackList(PageDomain pageDomain, Product product) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if(product.getName() != null){
            queryWrapper.like(Product::getName,product.getName());
        }
        if(product.getStatus() != null){
            queryWrapper.eq(Product::getStatus,product.getStatus());
        }
        if(product.getCate() != null){
            queryWrapper.eq(Product::getCate,product.getCate());
        }
        Page<Product> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        queryWrapper.eq(Product::getIsDeleted,ExistStatus.EXIST_STATUS.ordinal());
        queryWrapper.orderByDesc(Product::getUpdateTime);
        productMapper.selectPage(page,queryWrapper);
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setTotal(page.getTotal());
        dataInfo.setRows(page.getRecords());
        return dataInfo;
    }

    @Override
    public ProductVo getDetail(Long id) {
        ProductVo pvo = productMapper.getProductDetail(id, ProductStatus.TAKE_UP.ordinal(), ExistStatus.EXIST_STATUS.ordinal());
        String subImages = pvo.getSubImages();
        String storeSubImages = pvo.getStoreSubImages();
        String[] subImgs = subImages.split(";");
        String[] storeSubImgs = storeSubImages.split(";");
        Map<String,Object> map = new HashMap<>();
        map.put("subImages",subImgs);
        map.put("storeSubImages",storeSubImgs);
        pvo.setParams(map);
        return pvo;
    }



    // todo 情况特殊，现在未做保存图片和视频处理
    @Override
    public boolean updateOrSave(Product product) {
        Long userId = SecurityUtils.getUserId();
        Boolean hasStore = storeService.hasStore(userId, product.getStoreId());
        if(!hasStore){
            return false;
        }
        // 如果添加商品时未设置排序，默认是商品总数为顺序数
        Long sort = -1L;
        Long total = storeService.getProdTotal(product.getStoreId());
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(userId.toString());
        if(product.getSort() == null){
            sort = total;
        }else{
            // 当前排序不合法
            if(product.getSort() < 0){
                return false;
            }
            // 默认顺序不得大于商品总数
            if(product.getSort() > total){
                sort = total;
            }
            // 序列号小于总数的时候需要与之前的商品序号进行交换
            if(product.getSort() < total){
                sort = product.getSort().longValue();
                Product preProduct = getProductWithSort(product.getStoreId(), product.getSort());
                if(preProduct != null){
                    preProduct.setSort(total.intValue());
                    productMapper.updateById(preProduct);
                }
            }
        }
        product.setSort(sort.intValue());
        product.setStatus(ProductStatus.SUBMITED.ordinal());
        product.setIsDeleted(ExistStatus.EXIST_STATUS.ordinal());
        int i = -1;
        // 判断当前商店是否通过审核
        if(product.getStoreId() == null){
            return false;
        }
        Store store = storeService.getDetail(product.getStoreId());
        if(store == null || store.getStatus() != StoreStatus.PASS_AUDIT.ordinal()){
            return false;
        }
        // 新增
        if (product.getId() == null){
            product.setCreateBy(userId.toString());
            product.setCreateTime(DateUtils.getNowDate());
            i = productMapper.insert(product);
        }else{

            // 判断该商品是否是强制下架状态
            Product updateProduct = productMapper.selectById(product.getId());
            if(updateProduct.getStatus() == ProductStatus.MUST_TAKE_DOWN.ordinal()){
                return false;
            }
            // 修改商品后需要重新审核
            i = productMapper.updateById(product);
        }
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

//    删减库存
    @Override
    public synchronized Boolean decreaseStock(Long productId,Integer num){
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
//        判断库存是否大于下单量
        ProductVo pvo = getDetail(productId);
        if(pvo.getStock() < num){
            return false;
        }
        updateWrapper.eq(Product::getId,productId);
        updateWrapper.set(Product::getStock,pvo.getStock()-num);
        int update = productMapper.update(null, updateWrapper);
        if(update > 0){
            return true;
        }else{
            return false;
        }
    }

    //    增加库存
    @Override
    public Boolean addStock(Long productId,Integer num){
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
        ProductVo pvo = getDetail(productId);
        updateWrapper.eq(Product::getId,productId);
        updateWrapper.set(Product::getStock,pvo.getStock()+num);
        int update = productMapper.update(null, updateWrapper);
        if(update > 0){
            return true;
        }else{
            return false;
        }
    }

    // 查询某个商店下的某个序号是否有对应的商品
    public Product getProductWithSort(Long storeId,Integer sort){
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getStoreId,storeId)
                .eq(Product::getSort,sort);
        Product product = productMapper.selectOne(queryWrapper);
        return product;
    }

    /**
     * 查询某一商店不同状态下的商品列表
     * @param pageDomain
     * @param product
     * @return
     */
    @Override
    public TableDataInfo getList(PageDomain pageDomain,Product product) {
//        Long userId = SecurityUtils.getUserId();
//        根据商家查商店(目前只支持商家:商店=1：1)
//        Store store = storeService.selectByUserId(userId);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        TableDataInfo tableDataInfo = new TableDataInfo();
//        queryWrapper.select("select * distinct");
        queryWrapper
                .lambda()
                .eq(Product::getStoreId,product.getStoreId());

        // 分类查询
        if(product.getCate() != null) {
//            queryWrapper.lambda().eq(Product::getStatus,ProductStatus.TAKE_UP.ordinal());
            queryWrapper.lambda().eq(Product::getCate, product.getCate());
        }
        // 查询商品状态
        if(product.getStatus() != null){
            if(product.getStatus() == ProductStatus.MUST_TAKE_DOWN.ordinal()){
                tableDataInfo.setCode(500);
                tableDataInfo.setMsg("无法查询强制下架商品");
                return tableDataInfo;
            }
            queryWrapper.lambda().eq(Product::getStatus,product.getStatus());
        }
        queryWrapper.lambda().eq(Product::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        // 排序展示
        queryWrapper.lambda().orderByAsc(Product::getSort);
        Page<Product> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        productMapper.selectPage(page,queryWrapper);
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getCurrent()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public TableDataInfo getMainList(PageDomain pageDomain, Product product) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if(product.getSearchValue() != null && !product.getSearchValue().equals("")){
            queryWrapper.lambda().like(Product::getName,product.getSearchValue());
        }
        if(product.getCate() != null ){
            queryWrapper.lambda().eq(Product::getCate,product.getCate());
        }
        queryWrapper.lambda().eq(Product::getIsDeleted, ExistStatus.EXIST_STATUS.ordinal());
        queryWrapper.lambda().eq(Product::getStatus,ProductStatus.TAKE_UP.ordinal());
        queryWrapper.lambda().gt(Product::getStock,0);
        if (product.getParams() != null && !product.getParams().isEmpty()) {
            Iterator<Map.Entry<String, Object>> entries = product.getParams().entrySet().iterator();
            while(entries.hasNext()){
                Map.Entry<String,Object> val = entries.next();
                System.out.println(val.getKey()+' '+val.getValue());
                String key = val.getKey();
                Boolean isAsc = (Boolean)val.getValue();
                queryWrapper.orderBy(true,isAsc,key);
            }
        }
        Page<Product> page = new Page<>(pageDomain.getPageNum(),pageDomain.getPageSize());
        productMapper.selectPage(page,queryWrapper);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询到"+page.getRecords().size()+"条数据");
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    /**
     * 修改商品审核状态逻辑
     * @param product
     * @return
     */
    @Override
    public boolean updateProductStatus(Product product,Integer status) {
        Long userId = SecurityUtils.getUserId();
        // todo 当前版本如果商品为强制下架状态不能修改
        Product prod = productMapper.selectById(product.getId());
        if((prod.getStatus() == ProductStatus.SUBMITED.ordinal() && status == ProductStatus.AUDITING.ordinal())
            || (prod.getStatus() == ProductStatus.AUDITING.ordinal() && (status == ProductStatus.PASS_AUDIT.ordinal() || status == ProductStatus.NOPASS_AUDIT.ordinal()))
            || (prod.getStatus() == ProductStatus.SUBMITED.ordinal() && (status == ProductStatus.PASS_AUDIT.ordinal() || status == ProductStatus.NOPASS_AUDIT.ordinal()))
            || (prod.getStatus() == ProductStatus.PASS_AUDIT.ordinal() && status == ProductStatus.TAKE_UP.ordinal())
            || (prod.getStatus() == ProductStatus.TAKE_UP.ordinal() && status == ProductStatus.TAKE_DOWN.ordinal())
            || (prod.getStatus() == ProductStatus.TAKE_DOWN.ordinal() && status == ProductStatus.TAKE_UP.ordinal())
            || status == ProductStatus.MUST_TAKE_DOWN.ordinal()){
            LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .set(Product::getStatus, status)
                    .eq(Product::getId,product.getId());
            updateWrapper.set(Product::getUpdateTime, DateUtils.getNowDate());
            updateWrapper.set(Product::getUpdateBy,userId);
            int update = productMapper.update(null, updateWrapper);
            return update > 0?true:false;

        }else{
            return false;
        }

    }

    @Override
    public boolean deleteByIds(List<Long> idLongList) {
        for (Long id:idLongList
        ) {
            boolean b = deleteById(id);
            if(!b){
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long id) {
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Product::getIsDeleted, ExistStatus.NO_EXIST_STATUS.ordinal());
        updateWrapper.eq(Product::getId,id);
        int i = productMapper.update(null, updateWrapper);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }
}
